package com.wswy.wyjk.ui.main;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.my.httpapi.api.annotation.ViewL;
import com.my.httpapi.api.baseView.BaseActivity;
import com.wswy.wyjk.R;
import com.wswy.wyjk.api.Constant;
import com.wswy.wyjk.ui.share.ShareHelper;
import com.wswy.wyjk.utils.AdverConfigUtil;
import com.wswy.wyjk.utils.ChoosePicUtils;

import java.io.File;

@ViewL(R.layout.activity_webview)
public class WebViewActivity extends BaseActivity {

    private WebView webView;

    private String type;
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    private final static int FILECHOOSER_RESULTCODE = 10000;

    @Override
    protected void initData(Bundle savedInstanceState) {
        initData();
        initView();
    }

    @Override
    protected String showTitle() {
        type = getIntent().getStringExtra("type");
        if (TextUtils.isEmpty(type)) {
            type = "春运防疫政策查询";
        }
        return type;
    }

    @Override
    protected boolean statusBarIsBlack() {
        return true;
    }

    @Override
    protected void destroy() {
        webView.destroy();
    }

    @Override
    public void titleRightOnclick() {
        ShareHelper.shareApp(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent datas) {
        super.onActivityResult(requestCode, resultCode, datas);
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (mUploadCallbackAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, datas);
            }
        }
    }

    private void initData() {

    }

    @SuppressLint("JavascriptInterface")
    private void initView() {
        isShowTitleLeft(View.VISIBLE);
        webView = findViewById(R.id.webView);
        WebSettings webSettings = webView.getSettings();
        // 让WebView能够执行javaScript
        webSettings.setJavaScriptEnabled(true);
        //设置缓存模式
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        // 开启DOM storage API 功能
        webSettings.setDomStorageEnabled(true);
        // 开启database storage API功能
        webSettings.setDatabaseEnabled(true);
        webSettings.setAppCacheEnabled(true);
        //支持缩放，默认为true。
        webSettings.setSupportZoom(false);
        //调整图片至适合webview的大小
        webSettings.setUseWideViewPort(true);
        // 缩放至屏幕的大小
        webSettings.setLoadWithOverviewMode(true);
        //设置默认编码
        webSettings.setDefaultTextEncodingName("utf-8");
        //设置自动加载图片
        webSettings.setLoadsImagesAutomatically(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                setTitle(view.getTitle());
            }
        });
        webView.addJavascriptInterface(new JCInterface(this), "CcJsBridge");
        webView.setWebChromeClient(new WebChromeClient() {

            //
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                mUploadCallbackAboveL = filePathCallback;
                ChoosePicUtils.choosePic(WebViewActivity.this,FILECHOOSER_RESULTCODE);
                return true;
            }
        });

        switch (type) {
            case "用户协议":
                webView.loadUrl(getResources().getString(R.string.userAgreementUrl));
                break;
            case "隐私政策":
                webView.loadUrl(getResources().getString(R.string.privacyPolicyUrl));
                break;
            case "意见反馈":
                webView.loadUrl(Constant.feedbackUrl);
                break;
            case "春运防疫政策查询":
                if (TextUtils.isEmpty(AdverConfigUtil.homeBannerLinkUrl)) {
                    AdverConfigUtil.homeBannerLinkUrl = ShareHelper.shareUrl;
                }
                webView.loadUrl(AdverConfigUtil.homeBannerLinkUrl);
                setTitleIconRight(R.drawable.ic_share);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        webView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        webView.onResume();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if (requestCode != FILECHOOSER_RESULTCODE
                || mUploadCallbackAboveL == null) {
            return;
        }
        if (resultCode == RESULT_OK && PictureSelector.obtainMultipleResult(data).get(0) != null) {
            LocalMedia localMedia = PictureSelector.obtainMultipleResult(data).get(0);
            String albumPath = localMedia.getCompressPath();
            Uri result = Uri.fromFile(new File(albumPath));
            mUploadCallbackAboveL.onReceiveValue(new Uri[]{result});
        } else {
            mUploadCallbackAboveL.onReceiveValue(null);
        }
        mUploadCallbackAboveL = null;
        return;
    }
}
